import re

from .basic import BasicSchema
from ..selenium_driver import driver

from telethon.tl.functions.messages import GetBotCallbackAnswerRequest


class Visits_Loop(BasicSchema):
    def __init__(self, client, new_client, turple_rounds, CONST_NAMED_BOT):
        super().__init__(client, new_client, turple_rounds, CONST_NAMED_BOT)

    async def simple_open_site(self, url, client, tegmo):
        msg = ""
        driver.get(url)
        self.logging.info("[SELENIUM] Site opened.")
        await self.rand_sleep(int(1), int(3))
        response_msg = await self.client.get_messages(self.tegmo, limit=1)
        response_msg = response_msg[-1]
        try:
            elem = driver.find_element_by_tag_name("h6")
        except:
            elem = None
        if elem:
            if elem.text == "Please solve the reCAPTCHA to continue:":
                self.logging.info("Find reCAPTCHA")
                return False
        if re.search("Please stay on the site for at least ", response_msg.message):
            delay = response_msg.message.split("Please stay on the site for at least ")[
                -1
            ].split(" ")[0]
        elif re.search("You must stay on the site for", response_msg.message):
            delay = response_msg.message.split("You must stay on the site for ")[
                -1
            ].split(" ")[0]
        else:
            delay = 60
            msg = "[SELENIUM] Time not found, set max"

        if int(delay) >= 20:
            delay = int(delay) + 5

        self.logging.info(f"Sleeping for {delay}")
        if msg:
            self.logging.info(f"{msg}")

        await self.rand_sleep(int(delay), int(delay))
        self.logging.info("[SELENIUM] Done task")
        return True

    async def loop(self):
        # Базис - работа с /visit
        # Мб для чистоты кода нужно вынести добычу диалогов
        # Ноооо, мне лень
        while True:
            self.logging.info("New visit circle")
            await self.rand_sleep(1, 3)
            msg = await self.client.get_messages(self.tegmo, limit=1)
            msg = msg[-1]
            if self.round_loop > self.CONST_ROUNDS_TO_SLEEP:
                self.round_loop = 0
                self.logging.info("Sleep for many round")
                await self.rand_sleep(3600, 3600)
                # await self.withdraw()
            # Раунды, работают для сна некая защита от спама и бана телеги имхо безполезно
            self.round_loop += 1
            self.logging.info(f"New message, {msg.message[:10].encode()}")
            # Encode для смайликов - чтобы их коректно записать в файл и логгер не кричал об ошибках
            if re.search(r'Press the "Visit website"', msg.message):
                url = msg.reply_markup.rows[0].buttons[0].url
                await self.rand_sleep(1, 2)

                if not await self.simple_open_site(url, self.client, self.tegmo):
                    # Skip
                    button_data = msg.reply_markup.rows[1].buttons[1].data
                    message_id = msg.id
                    await self.client(
                        GetBotCallbackAnswerRequest(
                            self.tegmo, message_id, data=button_data
                        )
                    )
                    await self.rand_sleep(0, 3)
                    continue
                continue
            elif re.search(r"Sorry", msg.message):
                # Всяческие защиты от спама и бана, больше аккаунтов меньше counts
                # if self.total_sorry_round > 25:
                #     # Не важно в каком loop было получено sorry
                #     self.total_sorry_round = 0
                #     return self.total_sorry_round, self.round_loop
                if self.sorry_round > 5:
                    # Если в текущем loop
                    self.sorry_round = 0
                    return self.total_sorry_round, self.round_loop
                else:
                    # Условие по умолчанию
                    self.sorry_round += 1
                    self.total_sorry_round += 1
                    await self.client.send_message(
                        f"{self.CONST_NAMED_BOT} Click Bot", "/visit"
                    )
                    continue
            else:
                # Крайний вариант если бот отвечает не по шаблону
                await self.client.send_message(
                    f"{self.CONST_NAMED_BOT} Click Bot", "/visit"
                )
                await self.rand_sleep(2, 5)
                continue
